﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace cludg.Web.Core.ControllerFactory
{
	public class ControllerRegistry : IControllerRegistry
	{
		protected readonly Dictionary<string, Type> Controllers = new Dictionary<string, Type>();
		protected readonly List<IControllerProvider> Providers = new List<IControllerProvider>();

		public ControllerRegistry(IEnumerable<IControllerProvider> providers)
		{
			foreach (var provider in providers)
			{
				RegisterProvider(provider);
			}
		}

		protected void RegisterProvider(IControllerProvider provider)
		{
			Providers.Add(provider);
			foreach (var controller in provider.GetControllers())
			{
				Register(controller);
			}
		}

		public void Register(Type controller)
		{
			if (!typeof(IController).IsAssignableFrom(controller))
				throw new ArgumentException("Controller is not IController", "controller");

			var name = controller.Name;

			if (name.EndsWith("Controller"))
			{
				name = name.Substring(0, name.Length - "Controller".Length);
			}

			Controllers.Add(name, controller);
		}

		public void Register<TController>() where TController : IController
		{
			Register(typeof(TController));
		}

		public Type Get(string name)
		{
			return Controllers.ContainsKey(name) ? Controllers[name] : null;
		}
	}
}